﻿/**
 * jQuery EasyUI 1.4
 * 
 * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
 * 
 * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt To use it
 * on other terms please contact us at info@jeasyui.com
 * 选择题
 * question的结构
 * {
 * 	
 * }
 */
(function($) {
	var itemChar = "A".charCodeAt();
	function deleteObject(array,id) {
		if(array && array instanceof Array){
			for (var i = 0, len = array.length; i < len; i++) {
				if (array[i] == id) {
					array.splice(i, 1);
					return;
				}
			}
		}
	};
	
	function create(target){
		var choiceQuestion = $.data(target, 'choiceQuestion');
		var opts = choiceQuestion.options;
		$(target).qtiBox($.extend({}, opts, {
			cls:"choiceQuestion"
		}));
		var qtiBox = $.data(target, 'qtiBox');
		var qtiBoxOpts = qtiBox.options;
		$(target).addClass(qtiBoxOpts.status);
		
		//如果试题，内容为空，这给出初始化数据。
		if(qtiBoxOpts.question==null){
			qtiBoxOpts.question={
					id:null,
					isNew:true,
					keywords:"关键字",
					context:"题干内容",
					categoryItemId:null,
					type:opts.type,
					isADisplay:false
			};
			qtiBoxOpts.question.candidateAnswer=new Array();
			for(var i=0;i<4;i++){
				qtiBoxOpts.question.candidateAnswer.push({
					id:null,
					isNew:true,
					isCorrectAnswer:false,
					context:String.fromCharCode(itemChar+i),
					sortContext:String.fromCharCode(itemChar+i),
				});
			}
		}else if(qtiBoxOpts.question.isNew==true){
			if(qtiBoxOpts.question.candidateAnswer == undefined || qtiBoxOpts.question.candidateAnswer ==null){
				qtiBoxOpts.question.candidateAnswer=new Array();
				for(var i=0;i<4;i++){
					qtiBoxOpts.question.candidateAnswer.push({
						id:null,
						isNew:true,
						isCorrectAnswer:false,
						context:String.fromCharCode(itemChar+i),
						sortContext:String.fromCharCode(itemChar+i),
					});
				}
			}
		}else if(qtiBoxOpts.question.isNew==false){
			if(qtiBoxOpts.question.candidateAnswer == undefined || qtiBoxOpts.question.candidateAnswer ==null){
				qtiBoxOpts.question.candidateAnswer=new Array();
				for(var i=0;i<4;i++){
					qtiBoxOpts.question.candidateAnswer.push({
						id:null,
						isNew:true,
						isCorrectAnswer:false,
						sortContext:String.fromCharCode(itemChar+i),
						context:String.fromCharCode(itemChar+i),
					});
				}
			}
		}else{
			qtiBoxOpts.question={
					id:null,
					isNew:true,
					keywords:"关键字",
					context:"题干内容",
					categoryItemId:null,
					type:opts.type,
					isADisplay:false
			};
			qtiBoxOpts.question.candidateAnswer=new Array();
			for(var i=0;i<4;i++){
				qtiBoxOpts.question.candidateAnswer.push({
					id:null,
					isNew:true,
					isCorrectAnswer:false,
					sortContext:String.fromCharCode(itemChar+i),
					context:String.fromCharCode(itemChar+i),
				});
			}
		}
		loadQuestion(target, qtiBoxOpts.question);
	};
	
	//加载一个新的实体
	function loadQuestion(target,question){
		if(!question){
			return;
		}
		var qtiBox = $.data(target, 'qtiBox');
		var qtiBoxOpts = qtiBox.options;
		//创建题干
		createQtiPprompt(target,question);
		//创建虚拟键按钮
		var automaticDisplayBut=$("<div data-role=\"add-option\" data-edit=\"question\" class=\"add-option\"></div>");
		$(target).append(automaticDisplayBut);
		
		var automaticDisplayChecked=$("<input type=\"checkbox\">").bind("mousedown",function(){
			if(question.isADisplay){
				question.isADisplay=false;
			}else{
				question.isADisplay=true;
			}
		});
		if(question.isADisplay){
			$(automaticDisplayChecked).attr("checked","checked");
		}
		
		automaticDisplayBut.append(automaticDisplayChecked);
		automaticDisplayBut.append("是否显示选项（选中则在试卷中同时显示题干和选项，不选只显示题干）");
		//创建项
		var candidateAnswer=question.candidateAnswer;
		var olPanel=$("<ol class=\"plain block-listing solid choice-area\">");
		$(target).append(olPanel);
		for(var i=0;i<candidateAnswer.length;i++){
			var answer=candidateAnswer[i];
			createItem(olPanel,question,answer,i+1,false);
		}
		//创建虚拟键按钮
		var addOption=$("<div data-role=\"add-option\" data-edit=\"question\" class=\"add-option\"><span class=\"icon-add\"></span>添加选项</div>");
		
		$(target).append(addOption);
		addOption.bind("mousedown",function(){
			var answer={};
			question.candidateAnswer.push(answer);
			createItem(olPanel,question,answer,candidateAnswer.length,true);
		});
	
		//创建一个题干
		function createQtiPprompt(panel,question){
			var choiceQuestion = $.data(target, 'choiceQuestion');
			var opts = choiceQuestion.options;
			opts.promptNicEditor = $.fn.nicEditor({fullPanel : true});
			var container=opts.promptNicEditor.createEle("DIV").addClass("prompt qtiBox-prompt-container");
			$(target).append(container);
			$(container).css("position","relative");
			var context=opts.promptNicEditor.createEle("DIV").addClass("context qtiBox-prompt");
			context.appendTo(container);
			$(context).html(question.context);
			$(context).bind("mousedown",function(){
				if(qtiBoxOpts.status=="edit-answer"){
					return;
				}
				if(jQuery.trim($(context).html())=="题干内容"){
					$(context).html("");
				}
			});
			
			$(context).blur(function(){
				var str=$(context).html();
				if(jQuery.trim(str)==""){
					$(context).html("题干内容");
				}
			});
			var miniTlb=$("<div class=\"qtiBox-mini-tlb\"></div>");
			$(container).append(miniTlb);
			var aButton=$("<button type=\"button\" class=\"icon-font\"></button>");
			miniTlb.append(aButton);
			
			$(container).bind("mousedown",function(){
				if(qtiBoxOpts.status=="edit-answer"){
					return;
				}
				var containerTool=$(target).data("_containerTool");
				if(!containerTool){
					containerTool=opts.promptNicEditor.createEle("DIV").addClass("tool");
					$(containerTool).hide();
					containerTool.appendTo(container);
					opts.promptNicEditor.setPanel(containerTool);
					opts.promptNicEditor.addInstance(context);
					$(target).data("_containerTool",containerTool);
				
				}
				if(aButton.data("status-show")){
					if(containerTool){
						$(containerTool).show();
					}
				}
				aButton.show();
			});
			$(container).hover(function(){},function(){
				var containerTool=$(target).data("_containerTool");
				if(containerTool){
					$(containerTool).hide();
				};
				aButton.hide();
			});
			aButton.bind("mousedown",function(e){
				if(qtiBoxOpts.status!="edit-question"){
					return;
				}
				var status_show=aButton.data("status-show");
				var containerTool=$(target).data("_containerTool");
				if(!containerTool){
					containerTool=opts.promptNicEditor.createEle("DIV").addClass("tool");
					$(containerTool).hide();
					containerTool.appendTo(container);
					opts.promptNicEditor.setPanel(containerTool);
					opts.promptNicEditor.addInstance(context);
					$(target).data("_containerTool",containerTool);
				}
				if(status_show){
					aButton.data("status-show",false);
					$(containerTool).show();
				}else{
					aButton.data("status-show",true);
					$(containerTool).hide();
				}
			});
			if(qtiBoxOpts.status!="edit-question"){
				$(context).focus();
				aButton.show();
			}
			$(context).html(question.question);
			//设置当期的内容对象
			question.contextObj=$(context);
		}
		
		function createItem(olPanel,question,answer,index,isFocus){
			if (!answer) {
				return;
			}
			var choiceQuestion = $.data(target, 'choiceQuestion');
			var opts = choiceQuestion.options;
			var qtiBox = $.data(target, 'qtiBox');
			var qtiBoxOpts = qtiBox.options;
			var liPan=$("<li class=\"qtiBox-item qtiBox-simpleChoice "+qtiBoxOpts.status+"\"></li>");
			liPan.data("answer",answer);
			olPanel.append(liPan);
			var answerNicEditor = $.fn.nicEditor({fullPanel : true});
			var container=answerNicEditor.createEle("DIV").addClass("container qtiBox-answer-container");
			liPan.append(container);
			$(container).css("position","relative");
			
			var item=$("<div class=\"qtiBox-item-box\"></div>");
			$(container).append(item);
			//
			var label=$("<label class=\"real-label\"></label>");
			//设置是否，正确答案
			var inputStr=["<input answer=\"true\" disabled=\"disabled\""];
			if(answer.isCorrectAnswer){
				inputStr.push(" isChecked=\"true\" ");
			}else{
				inputStr.push(" isChecked=\"false\" ");
			}
			if(opts.isMultiple){
				inputStr.push("type=\"checkbox\">");
			}else{
				inputStr.push("type=\"radio\">");
			}
			var checkbox=$(inputStr.join(""));
			checkbox.unbind().bind("change",function(){
				if(this.checked){
					if(opts.isMultiple==false){
						var cd=olPanel.find("input[answer]");
						cd.prop("checked",false);
						cd.attr("isChecked","false");
						for(var i=0;i<question.candidateAnswer.length;i++){
							var answerolad=question.candidateAnswer[i];
							answerolad.isCorrectAnswer=false;
						}
					}
					answer.isCorrectAnswer=true;
					$(this).attr("isChecked","true");
					this.checked=true;
				}else{
					answer.isCorrectAnswer=false;
					$(this).attr("isChecked","false");
				}
			});
			
			item.append(label.append(checkbox));
			var context=answerNicEditor.createEle("DIV").addClass("context answer-context");
			$(context).appendTo(item);
			$(context).html(answer.context);
			//设置内容对象
			answer.contextObj=$(context);
			
			var miniTlb=$("<div class=\"qtiBox-mini-tlb item-tlb\"></div>");
			$(container).append(miniTlb);
			
			var delButton=$("<button type=\"button\" class=\"icon-bin\"></button>");
			var aButton=$("<button type=\"button\" style=\"display: none;\" class=\"icon-font\"></button>");
			miniTlb.append(delButton);
			
			delButton.bind("mousedown",function(e){
				if(qtiBoxOpts.status!="edit-question"){
					return;
				}
				deleteObject(question.candidateAnswer,answer);
				liPan.data("answer",null);
				liPan.remove();
			});
			
			miniTlb.append(aButton);
			
			$(liPan).hover(function(){},function(e){
				var pl=$(e.target).closest('li.qtiBox-item');
				if (pl.hasClass('edit-active')){
					pl.removeClass('edit-active');
				}
				if ($(context).hasClass('cke_focus')){
					$(context).removeClass('cke_focus');
				}
				aButton.hide();
				var containerTool=$(liPan).data("_containerTool");
				if(containerTool){
					$(containerTool).hide();
				}
				e.stopPropagation();
			});
			
			$(context).bind("mousedown", function(e) {
				if(qtiBoxOpts.status=="edit-answer"){
					return;
				}
				if (!liPan.hasClass('edit-active')){
					liPan.addClass('edit-active');
				}
				if (!$(context).hasClass('cke_focus')){
					$(context).addClass('cke_focus');
				}
				
				var containerTool=$(liPan).data("_containerTool");
				if(!containerTool){
					containerTool=answerNicEditor.createEle("DIV").addClass("tool");
					$(containerTool).hide();
					containerTool.appendTo(container);
					answerNicEditor.setPanel(containerTool);
					answerNicEditor.addInstance(context);
					$(liPan).data("_containerTool",containerTool);
				}
				if(aButton.data("status-show")){
					$(containerTool).show();
				}
				aButton.show();
			});
			
			aButton.bind("mousedown",function(e){
				if(qtiBoxOpts.status!="edit-question"){
					return;
				}
				var status_show=aButton.data("status-show");
				var containerTool=$(liPan).data("_containerTool");
				if(!containerTool){
					containerTool=answerNicEditor.createEle("DIV").addClass("tool");
					$(containerTool).hide();
					containerTool.appendTo(container);
					answerNicEditor.setPanel(containerTool);
					answerNicEditor.addInstance(context);
					$(liPan).data("_containerTool",containerTool);
				}
				
				if(status_show){
					aButton.data("status-show",false);
					$(containerTool).hide();
				}else{
					aButton.data("status-show",true);
					$(containerTool).show();
				}
			});
			if(isFocus && qtiBoxOpts.status!="edit-question"){
				$(context).focus();
				if (!liPan.hasClass('edit-active')){
					liPan.addClass('edit-active');
				}
				if (!$(context).hasClass('cke_focus')){
					$(context).addClass('cke_focus');
				}
				aButton.show();
			}
		}
	}
	
	$.fn.choiceQuestion = function(method, options) {
		if (typeof method == "string") {
			var methodBox =  $.fn.choiceQuestion.methods[method];
			if (methodBox){
				return methodBox(this, options);
			} else {
				return this.qtiBox(method, options);
			}
		}
		method = method || {};
		return this.each(function() {
			var choiceQuestion = $.data(this, "choiceQuestion");
			var opts;
			if (choiceQuestion) {
				opts = $.extend(choiceQuestion.options, method);
				choiceQuestion.isLoaded = false;
			} else {
				opts = $.extend({}, $.fn.choiceQuestion.defaults, $.fn.choiceQuestion.parseOptions(this), method);
				$(this).attr("title", "");
				choiceQuestion = $.data(this, "choiceQuestion", {
					options : opts,
					isLoaded : false
				});
			}
			create(this);
		});
	};
	$.fn.choiceQuestion.methods = {
		options : function(jq) {
			return $.data(jq[0], "choiceQuestion").options;
		},
		createContent:function(jq){
			return jq.each(function(){
				createContent(this);
			});
		},toJson:function(jq,question){
			return jq.each(function() {
				var opts=$.data(this, "choiceQuestion").options;
				return opts.questions;
			});
		}
	};
	$.fn.choiceQuestion.parseOptions = function(target) {
		return $.extend({}, $.fn.qtiBox.parseOptions(target));
	};
	
	$.fn.choiceQuestion.defaults = $.extend({}, $.fn.qtiBox.defaults, {
		questionButEvent:function(target){
			$(target).qtiBox("setStatusEdit");
			$(target).find(".real-label>input").attr("disabled","disabled").removeAttr("checked");
		},
		clearAnswerCall:function(target){
			$(target).find(".real-label>input").attr("disabled","disabled").removeAttr("checked");
		},
		responseButEvent:function(target){
			$(target).qtiBox("setStatusAnswer");
			$(target).find(".real-label>input").removeAttr("disabled").each(function(){
				var isChecked=$(this).attr("isChecked");
				if(isChecked && isChecked=="true"){
					this.checked=true;
				}else{
					$(this).removeAttr("checked");
				}
			});
		},
		isMultiple:true,
		nicEditor:null,
		nicEditorPanel:null,
		instanceArray:null,
		contentCall:function(target){
		}
	});
})(jQuery);
